package cn.com.sbell.vss.csg.vsclient.ipcamera;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

import cn.com.sbell.vss.VssConstants;
import cn.com.sbell.vss.VssException;
import cn.com.sbell.vss.csg.vap.bean.DeviceInfo;
import cn.com.sbell.vss.csg.vap.bean.GPIODeviceInfo;
import cn.com.sbell.vss.csg.vap.bean.IPCameraInfo;
import cn.com.sbell.vss.csg.vap.bean.IpCameraAlarmCofig;
import cn.com.sbell.vss.csg.vap.bean.NTPInfo;
import cn.com.sbell.vss.csg.vap.bean.NetworkCfgIn;
import cn.com.sbell.vss.csg.vap.bean.NetworkCfgOut;
import cn.com.sbell.vss.csg.vap.bean.PresetPTZ;
import cn.com.sbell.vss.csg.vap.bean.PtzCommander;
import cn.com.sbell.vss.csg.vap.bean.TimeInfo;
import cn.com.sbell.vss.csg.vap.bean.UserInfo;
import cn.com.sbell.vss.csg.vap.bean.GPIODeviceInfo.ChannelInfo;
import cn.com.sbell.vss.csg.vap.bean.NetworkCfgOut.Ethernet;
import cn.com.sbell.vss.csg.vsclient.AbstractVsClient;
import cn.com.sbell.vss.csg.vsclient.AccessInfo;
import cn.com.sbell.vss.csg.vsclient.util.BeanValidator;
import cn.com.sbell.vss.csg.vsclient.util.CSGConfiguration;
import cn.com.sbell.vss.csg.vsclient.util.PropertiesHolder;

public class IPCameraClient extends AbstractVsClient {
	private HttpClient httpClient;

	private int statusCode = 0;

	private static final String SET_RETURN_CODE_KEY = "Return";

	private static final String KIND = "1";

	private static final String PATTERN_TIMESTAMP = "yyyyMMddHHmm";

	// private static Map modelMap = Collections.synchronizedMap(new HashMap());

	public IPCameraClient(AccessInfo access) {
		super(access);
		httpClient = new HttpClient();
		HostConfiguration hostConfiguration = new HostConfiguration();
		hostConfiguration.setHost(new HttpHost(access.vsIp, access.vsPort
				.intValue()));
		httpClient.setHostConfiguration(hostConfiguration);
		httpClient.getParams().setAuthenticationPreemptive(true);
		Credentials defaultcreds = new UsernamePasswordCredentials(
				access.vsLoginUsername, access.vsLoginPassword);
		httpClient.getState().setCredentials(
				new AuthScope(access.vsIp, access.vsPort.intValue(),
						AuthScope.ANY_REALM), defaultcreds);
		SimpleHttpConnectionManager shcm=new SimpleHttpConnectionManager();
		HttpConnectionManagerParams hcmp=new HttpConnectionManagerParams();
		hcmp.setConnectionTimeout(CSGConfiguration.PU_CONNECTION_TIMEOUT);
		hcmp.setDefaultMaxConnectionsPerHost(1);
		hcmp.setLinger(CSGConfiguration.PU_SO_LINGER);
		hcmp.setMaxTotalConnections(1);
		hcmp.setSoTimeout(CSGConfiguration.PU_SO_TIMEOUT);
		shcm.setParams(hcmp);
		httpClient.setHttpConnectionManager(shcm);
		httpClient.getParams().setContentCharset(VssConstants.DEFAULT_ENCODINIG);
	}

	public void close() {

	}

	public boolean controlPtz(PtzCommander ptzCmder) {

		// BeanValidator.validateNotNull(ptzCmder, new String[] {
		// "productVersion" });
		String productVersion = access.getVsProductVersion();
	try {
		String[] cmd = IpCameraPtzCommandSet.getPtzCommand(ptzCmder.getCmd());
		HttpMethod method = IpCameraPtzCommandSet.createCommandMethod(cmd,
				ptzCmder, productVersion);
		Thread controlPtzThread = new ControlPtzThread(method, httpClient);
		controlPtzThread.start();
	} catch (VssException e) {
		// TODO: handle exception
		if(VssConstants.CODE_UNSUPPORTED_PTZ_PROTOCOL_COMMAND.equals(e.getResultCode())
				&&"STOP".equals(ptzCmder.getCmd()))
		{
			logger.debug("client send IPCAM STOP, not yet supported");
		}else{
			throw e;
		}
	}	

		/**
		 * executeMethod(method);if (method.getStatusCode() == 200) { return
		 * true; } else { return false; }
		 */
		return true;

	}

	public boolean controlVs(int action) {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			GetMethod method = new GetMethod("/nphRestart");
			method
					.setQueryString(new NameValuePair[] {
							new NameValuePair(VssConstants.METHOD_PARAMETER,
									"Restart"),
							new NameValuePair("Restart", "OK") });
			executeMethod(method);
			return executeMethod(method);
		} else {
			GetMethod method = new GetMethod("/Set");
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("Func", "Restart"),
					new NameValuePair("Kind", KIND),
					new NameValuePair("Data", "OK") });

			String result = executeMethodForString(method);
			PropertiesHolder holder = new PropertiesHolder();
			holder.load(result);
			return VssConstants.RESULT_NORMAL_STATUS.equals(holder
					.getStrProperty(SET_RETURN_CODE_KEY));
		}

	}

	public IPCameraInfo getIPCameraInfo() {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			throw new VssException(
					VssConstants.CODE_UNSUPPORTED_EQUIPMENT_COMMAND);
		} else {
			IPCameraInfo cameraInfo = new IPCameraInfo();
			PropertiesHolder[] holder = new PropertiesHolder[6];

			holder[0] = new PropertiesHolder();
			holder[0].load(executeMethodForString(createGetMethod("CameraWB",
					KIND)));
			cameraInfo.setWhiteBalance(holder[0].getIntProperty("Data"));

			holder[1] = new PropertiesHolder();
			holder[1].load(executeMethodForString(createGetMethod("NightView",
					KIND)));
			cameraInfo.setEnableNightView(holder[1].getIntProperty("Data"));

			holder[2] = new PropertiesHolder();
			holder[2].load(executeMethodForString(createGetMethod("PowerLed",
					KIND)));
			cameraInfo.setLedPower(holder[2].getIntProperty("Data"));

			holder[3] = new PropertiesHolder();
			holder[3].load(executeMethodForString(createGetMethod("Doutput",
					KIND)));
			cameraInfo.setOutputStatus(holder[3].getIntProperty("Data"));

			holder[4] = new PropertiesHolder();
			holder[4].load(executeMethodForString(createGetMethod("Powerfrq",
					KIND)));
			cameraInfo.setPowerFreq(holder[4].getIntProperty("Data"));

			holder[5] = new PropertiesHolder();

			GetMethod panMethod = createGetMethod("Pan", KIND);
			String panResult = executeMethodForString(panMethod);
			holder[5].load(panResult);
			cameraInfo.setPanHome(holder[5].getIntProperty("PanHome"));
			cameraInfo.setPanRM(holder[5].getIntProperty("PanRM"));
			cameraInfo.setPanRP(holder[5].getIntProperty("PanRP"));
			GetMethod tiltMethod = createGetMethod("Tilt", KIND);
			String tiltResult = executeMethodForString(tiltMethod);
			holder[5].load(tiltResult);
			cameraInfo.setTiltHome(holder[5].getIntProperty("TiltHome"));
			cameraInfo.setTiltRM(holder[5].getIntProperty("TiltRM"));
			cameraInfo.setTiltRP(holder[5].getIntProperty("TiltRP"));

			return cameraInfo;
		}

	}

	public GPIODeviceInfo getInOutDev() {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			throw new VssException(
					VssConstants.CODE_UNSUPPORTED_EQUIPMENT_COMMAND);
		} else {
			GPIODeviceInfo gpioDeviceInfo = new GPIODeviceInfo();
			PropertiesHolder holder = new PropertiesHolder();
			String result = executeMethodForString(createGetMethod("Sensor",
					KIND));
			holder.load(result);
			ChannelInfo channelInfo = new ChannelInfo();
			channelInfo.setChannelNumber(new Integer(1));
			channelInfo.setChannelType(GPIODeviceInfo.OUTPUT);
			channelInfo.setState(holder.getIntProperty("Data"));
			gpioDeviceInfo.setInput(new ChannelInfo[] {});
			gpioDeviceInfo.setOutput(new ChannelInfo[] { channelInfo });

			return gpioDeviceInfo;
		}

	}

	public int getLastStatusCode() {

		return statusCode;
	}

	public NTPInfo getNTP() {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			throw new VssException(
					VssConstants.CODE_UNSUPPORTED_EQUIPMENT_COMMAND);
		} else {
			NTPInfo ntpInfo = new NTPInfo();
			PropertiesHolder holder = new PropertiesHolder();
			String result = executeMethodForString(createGetMethod("Ntp", KIND));
			holder.load(result);
			ntpInfo.setNtpEnable(holder.getIntProperty("NtpEnable"));
			ntpInfo.setNtpHost(holder.getStrProperty("NtpServer"));
			ntpInfo.setTimeZone(holder.getIntProperty("TimeZone"));
			return ntpInfo;
		}

	}

	public NetworkCfgOut getNetworkInfo() {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			throw new VssException(
					VssConstants.CODE_UNSUPPORTED_EQUIPMENT_COMMAND);
		} else {
			NetworkCfgOut netWork = new NetworkCfgOut();
			PropertiesHolder holder = new PropertiesHolder();
			String result = executeMethodForString(createGetMethod("Network",
					KIND));
			holder.load(result);
			Ethernet etherNet = new Ethernet();
			etherNet.setIpAddress(holder.getStrProperty("IP"));
			etherNet.setNetId(new Integer(1));
			etherNet.setNetMask(holder.getStrProperty("Netmask"));
			etherNet.setPort(holder.getIntProperty("Port"));

			netWork.setEthernet(new Ethernet[] { etherNet });
			netWork.setDns(new String[] { holder.getStrProperty("DNS1"),
					holder.getStrProperty("DNS2") });
			netWork
					.setGateway(new String[] { holder.getStrProperty("Gateway") });
			netWork.setBandwidth(holder.getStrProperty("Bandwidth"));
			netWork.setConnectionMode(holder.getStrProperty("ConnectType"));
			netWork.setNetMode(holder.getIntProperty("Mode"));
			return netWork;
		}

	}

	public PresetPTZ[] getPresetPTZ(int ptzId) {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			throw new VssException(
					VssConstants.CODE_UNSUPPORTED_EQUIPMENT_COMMAND);
		} else {
			List ptzList = new ArrayList();
			PropertiesHolder holder = null;
			GetMethod method = null;
			String result = null;
			PresetPTZ ptz = null;
			for (int i = 0; i < VssConstants.PTZ_MAX_NUMBER; i++) {
				holder = new PropertiesHolder();
				method = createGetMethod("PresetName", String.valueOf(i + 1));
				result = executeMethodForString(method);
				holder.load(result);
				if (holder.getStrProperty("Data") != null && !"".equals(holder.getStrProperty("Data"))) {
					ptz = new PresetPTZ();
					ptz.setPresetIndex(new Integer(i + 1));
					try {
						ptz.setPresetName(holder.getStrProperty("Data") == null ? ""
								: new String(holder.getStrProperty(
								"Data").getBytes("iso-8859-1"),
								"GB2312"));				

					} catch (UnsupportedEncodingException e) {
						// e.printStackTrace();
					}
					ptzList.add(ptz);
				}

			}
			return (PresetPTZ[]) ptzList.toArray(new PresetPTZ[0]);
		}

	}

	public TimeInfo getTime() {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			throw new VssException(
					VssConstants.CODE_UNSUPPORTED_EQUIPMENT_COMMAND);
		} else {
			TimeInfo timeInfo = new TimeInfo();
			PropertiesHolder holder = new PropertiesHolder();
			String result = executeMethodForString(createGetMethod("Date", KIND));
			holder.load(result);
			String date = holder.getStrProperty("Data");
			if (date != null && date.length() == 18) {
				timeInfo.setYear(new Integer(date.substring(0, 4)));
				timeInfo.setMonth(new Integer(date.substring(4, 6)));
				timeInfo.setDate(new Integer(date.substring(6, 8)));
				timeInfo.setHour(new Integer(date.substring(9, 11)));
				timeInfo.setMinute(new Integer(date.substring(11, 13)));
				timeInfo.setSecond(new Integer(date.substring(13, 15)));
			}

			return timeInfo;
		}

	}

	public void init() {

	}

	public DeviceInfo requestVsDeviceInfo() {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			throw new VssException(
					VssConstants.CODE_UNSUPPORTED_EQUIPMENT_COMMAND);
		} else {
			PropertiesHolder holder = new PropertiesHolder();
			DeviceInfo deviceInfo = new DeviceInfo();
			String result = executeMethodForString(createGetMethod("Model",
					KIND));
			holder.load(result);
			deviceInfo.setSoftWareVersion(holder.getStrProperty("AplFirm"));
			deviceInfo.setModelName(holder.getStrProperty("ModelName"));
			return deviceInfo;
		}

	}

	public boolean setIPCameraInfo(IPCameraInfo ipCameraInfo) {
		String productVersion = access.getVsProductVersion();
		BeanValidator.validatePanRange(ipCameraInfo, new String[] { "panRM",
				"panRP", "panHome" }, productVersion);
		BeanValidator.validateTiltRange(ipCameraInfo, new String[] { "tiltRM",
				"tiltRP", "tiltHome" }, productVersion, ipCameraInfo
				.getSetupType());

		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			NameValuePair[] tilt = null;
			if (VssConstants.DATA_INTEGER == ipCameraInfo.getSetupType()
					.intValue()) {
				ipCameraInfo
						.setSetupType(new Integer(VssConstants.DATA_STRING));
				tilt = new NameValuePair[] {
						new NameValuePair("TiltRangeMinusTab", ipCameraInfo
								.getTiltRM().toString()),
						new NameValuePair("TiltHomeTab", ipCameraInfo
								.getTiltHome().toString()),
						new NameValuePair("TiltRangePlusTab", ipCameraInfo
								.getTiltRP().toString()) };
			} else {
				ipCameraInfo
						.setSetupType(new Integer(VssConstants.DATA_INTEGER));
				tilt = new NameValuePair[] {
						new NameValuePair("TiltRangeMinusCeil", ipCameraInfo
								.getTiltRM().toString()),
						new NameValuePair("TiltHomeCeil", ipCameraInfo
								.getTiltHome().toString()),
						new NameValuePair("TiltRangePlusCeil", ipCameraInfo
								.getTiltRP().toString()) };
			}

			GetMethod method = new GetMethod(VssConstants.METHOD_NAME);
			method.setQueryString(new NameValuePair[] {
					new NameValuePair(VssConstants.METHOD_PARAMETER,
							"CameraSetup"),
					new NameValuePair("WhiteBalance", ipCameraInfo
							.getWhiteBalance().toString()),
					new NameValuePair("PowLineFreq", "50"),
					new NameValuePair("CameraBright",
							VssConstants.RESULT_NORMAL_STATUS),
					new NameValuePair("NightViewControl",
							VssConstants.RESULT_FORMAT_STATUS),
					new NameValuePair("CameraControl",
							VssConstants.RESULT_NORMAL_STATUS),
					new NameValuePair("Preset",
							VssConstants.RESULT_NORMAL_STATUS),
					new NameValuePair("PresetControl",
							VssConstants.RESULT_NORMAL_STATUS),
					new NameValuePair("ZoomControl",
							VssConstants.RESULT_NORMAL_STATUS),
					new NameValuePair("FocusControl",
							VssConstants.RESULT_NORMAL_STATUS),
					new NameValuePair("PanRangeMinus", ipCameraInfo.getPanRM()
							.toString()),
					new NameValuePair("PanHome", ipCameraInfo.getPanHome()
							.toString()),
					new NameValuePair("PanRangePlus", ipCameraInfo.getPanRP()
							.toString()),
					new NameValuePair("Layout", ipCameraInfo.getSetupType()
							.toString()), tilt[0], tilt[1], tilt[2],
					new NameValuePair("Save", "ON") });
			executeMethod(method);

			GetMethod dgmethod = new GetMethod(VssConstants.METHOD_NAME);
			method.setQueryString(new NameValuePair[] {
					new NameValuePair(VssConstants.METHOD_PARAMETER,
							"DigitalOutputControl"),
					new NameValuePair("DigitalOutput", ipCameraInfo
							.getOutputStatus().toString()),
					new NameValuePair("Save", "ON") });
			executeMethod(dgmethod);

			return true;

		} else {
			boolean status = false;

			PropertiesHolder holder = new PropertiesHolder();

			holder.load(executeMethodForString(createSetMethod("CameraWB",
					ipCameraInfo.getWhiteBalance().toString())));

			if (!productVersion.startsWith(VssConstants.MODEL_TYPE)
					&& !productVersion.startsWith(VssConstants.MODEL_10TYPE)) {

				holder.load(executeMethodForString(createSetMethod("NightView",
						ipCameraInfo.getEnableNightView().toString())));

			}
			if (!productVersion.startsWith(VssConstants.MODEL_10TYPE)) {

				holder.load(executeMethodForString(createSetMethod("PowerLed",
						ipCameraInfo.getLedPower().toString())));

			}

			if (!productVersion.startsWith(VssConstants.MODEL_TYPE)
					&& !productVersion.startsWith(VssConstants.MODEL_10TYPE)) {

				holder.load(executeMethodForString(createSetMethod("Doutput",
						ipCameraInfo.getOutputStatus().toString())));

			}

			holder
					.load(executeMethodForString(createSetMethod("Powerfrq",
							"50")));

			GetMethod panMethod = new GetMethod("/Set");
			panMethod.setQueryString(new NameValuePair[] {
					new NameValuePair("Func", "Pan"),
					new NameValuePair("Kind", KIND),
					new NameValuePair("PanRM", ipCameraInfo.getPanRM()
							.toString()),
					new NameValuePair("PanHome", ipCameraInfo.getPanHome()
							.toString()),
					new NameValuePair("PanRP", ipCameraInfo.getPanRP()
							.toString()) });
			holder.load(executeMethodForString(panMethod));

			GetMethod tiltMethod = new GetMethod("/Set");
			tiltMethod.setQueryString(new NameValuePair[] {
					new NameValuePair("Func", "Tilt"),
					new NameValuePair("Kind", KIND),
					new NameValuePair("TiltRM", ipCameraInfo.getTiltRM()
							.toString()),
					new NameValuePair("TiltHome", ipCameraInfo.getTiltHome()
							.toString()),
					new NameValuePair("TiltRP", ipCameraInfo.getTiltRP()
							.toString()) });
			holder.load(executeMethodForString(tiltMethod));

			String[] result = holder.getStrProperties(SET_RETURN_CODE_KEY);
			for (int i = 0; i < result.length; i++) {
				if (VssConstants.RESULT_NORMAL_STATUS.equals(result[i])) {
					status = true;
				} else {
					status = false;
				}
			}

			return status;
		}

	}

	public boolean setNTP(NTPInfo ntpInfo) {
		BeanValidator.validateNotNull(ntpInfo, new String[] { "ntpEnable",
				"ntpHost", "timeZone" });
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			return true;
		} else {
			PropertiesHolder holder = new PropertiesHolder();
			GetMethod method = new GetMethod("/Set");
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("Func", "Ntp"),
					new NameValuePair("Kind", KIND),
					new NameValuePair("NtpEnable", String.valueOf(ntpInfo
							.getNtpEnable())),
					new NameValuePair("NtpServer", ntpInfo.getNtpHost()),
					new NameValuePair("TimeZone", ntpInfo.getTimeZone()
							.toString()) });
			String result = executeMethodForString(method);
			holder.load(result);
			return VssConstants.RESULT_NORMAL_STATUS.equals(holder
					.getStrProperty(SET_RETURN_CODE_KEY));
		}

	}

	public boolean setNetworkInfo(NetworkCfgIn networkCfg) {
		String gateWay = "";
		String[] dns = new String[] { "", "" };
		try {
			gateWay = networkCfg.getGateway()[0];

		} catch (Exception e) {

		}
		try {
			for (int i = 0; i < dns.length; i++) {
				dns[i] = networkCfg.getDns()[i];
			}
		} catch (Exception e1) {

		}
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			GetMethod method = new GetMethod(VssConstants.METHOD_NAME);

			method
					.setQueryString(new NameValuePair[] {
							new NameValuePair(VssConstants.METHOD_PARAMETER,
									"Network"),
							new NameValuePair("CameraBootpEnable", "Check"),
							new NameValuePair("CameraPort", networkCfg
									.getPort().toString()),
							new NameValuePair("CameraIP", networkCfg
									.getIpAddress()),
							new NameValuePair("CameraNetmask", networkCfg
									.getSubnetMask()),
							new NameValuePair("CameraInternetFlag",
									VssConstants.RESULT_FORMAT_STATUS),
							new NameValuePair("CameraGateway", gateWay),
							new NameValuePair("CameraDNS1", dns[0]),
							new NameValuePair("CameraDNS2", dns[1]),
							new NameValuePair("CameraConnectionType",
									networkCfg.getConnectionMode()),
							new NameValuePair("CameraBandwidth", networkCfg
									.getBandwidth()),
							new NameValuePair("Save", "ON") });

			return executeMethod(method);
		} else {
			PropertiesHolder holder = new PropertiesHolder();

			GetMethod method = new GetMethod("/Set");
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("Func", "Network"),
					new NameValuePair("Kind", KIND),
					new NameValuePair("Mode", "2"),
					new NameValuePair("Port", networkCfg.getPort().toString()),
					new NameValuePair("IP", networkCfg.getIpAddress()),
					new NameValuePair("Netmask", networkCfg.getSubnetMask()),
					new NameValuePair("Gateway", gateWay),
					new NameValuePair("DNS1", dns[0]),
					new NameValuePair("DNS2", dns[1]),
					new NameValuePair("Bandwidth", networkCfg.getBandwidth()),
					new NameValuePair("ConnectType", networkCfg
							.getConnectionMode()) });
			String result = executeMethodForString(method);
			holder.load(result);
			return VssConstants.RESULT_NORMAL_STATUS.equals(holder
					.getStrProperty(SET_RETURN_CODE_KEY));
		}

	}

	public boolean setPresetPTZ(PresetPTZ preset) {
		if (preset.getPresetName() != null) {
			BeanValidator.validateProp(preset, new String[] { "presetName" },
					1, 15);
		}
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			if (preset.getPresetIndex().intValue() > 8
					|| preset.getPresetIndex().intValue() < 1) {
				throw new VssException(VssConstants.CODE_INVALID,
						new String[] { "csg.presetIndex" });
			}
			if (preset.getPresetName() != null) {
				GetMethod method = new GetMethod("/nphPresetNameCheck");
				method
						.setQueryString(new NameValuePair[] {
								new NameValuePair("PresetName", preset
										.getPresetName()),
								new NameValuePair("Data", preset
										.getPresetIndex().toString()) });
				return executeMethod(method);
			} else {
				GetMethod method = new GetMethod("/nphPresetNameCheck");
				method.setQueryString(new NameValuePair[] { new NameValuePair(
						"Data", preset.getPresetIndex().toString()) });
				return executeMethod(method);
			}
		} else {

			PropertiesHolder holder = new PropertiesHolder();
			GetMethod method = new GetMethod("/Set");
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("Func", "PresetName"),
					new NameValuePair("Kind", preset.getPresetIndex()
							.toString()),
					new NameValuePair("Data", preset.getPresetName()) });
			String result = executeMethodForString(method);
			holder.load(result);
			return VssConstants.RESULT_NORMAL_STATUS.equals(holder
					.getStrProperty(SET_RETURN_CODE_KEY));
		}

	}

	public boolean setTime(TimeInfo timeInfo) {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			DecimalFormat dformat = new DecimalFormat("0");
			GetMethod method = new GetMethod(VssConstants.METHOD_NAME);
			method
					.setQueryString(new NameValuePair[] {
							new NameValuePair(VssConstants.METHOD_PARAMETER,
									"NameTime"),
							new NameValuePair("HeadingName", "KX"),
							new NameValuePair("Year", dformat.format(Integer
									.parseInt(timeInfo.getYear().toString()
											.substring(2)))),
							new NameValuePair("Month", timeInfo.getMonth()
									.toString()),
							new NameValuePair("Day", timeInfo.getDate()
									.toString()),
							new NameValuePair("Hour", timeInfo.getHour()
									.toString()),
							new NameValuePair("Minute", timeInfo.getMinute()
									.toString()),
							new NameValuePair("Save", "ON") });
			return executeMethod(method);
		} else {
			PropertiesHolder holder = new PropertiesHolder();
			GetMethod method = new GetMethod("/Set");
			String date = dateFormat(timeInfo);
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("Func", "Date"),
					new NameValuePair("Kind", KIND),
					new NameValuePair("Data", date) });
			String result = this.executeMethodForString(method);
			holder.load(result);
			return VssConstants.RESULT_NORMAL_STATUS.equals(holder
					.getStrProperty(SET_RETURN_CODE_KEY));
		}

	}

	public boolean setUser(UserInfo userInfo) {
		if (GetIpCameraVersion.getType(access.getVsProductVersion())) {
			BeanValidator.validateProp(userInfo, new String[] { "name",
					"password" }, 4, 15);
			GetMethod method = new GetMethod(VssConstants.METHOD_NAME);
			method.setQueryString(new NameValuePair[] {
					new NameValuePair(VssConstants.METHOD_PARAMETER,
							"SecurityAdministrator"),
					new NameValuePair("AuthenticationEnable",
							VssConstants.RESULT_FORMAT_STATUS),
					new NameValuePair("AdministratorID", userInfo.getName()),
					new NameValuePair("AdministratorPassword1", userInfo
							.getPassword()),
					new NameValuePair("AdministratorPassword1", userInfo
							.getPassword()), new NameValuePair("Save", "ON") });
			return executeMethod(method);
		} else {
			BeanValidator.validateProp(userInfo, new String[] { "name",
					"password" }, 6, 15);
			PropertiesHolder holder = new PropertiesHolder();
			GetMethod method = new GetMethod("/Set");
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("Func", "Admin"),
					new NameValuePair("Kind", KIND),
					new NameValuePair("Mode", "3"),
					new NameValuePair("ID", userInfo.getName()),
					new NameValuePair("Pass", userInfo.getPassword()) });
			String result = executeMethodForString(method);
			holder.load(result);
			return VssConstants.RESULT_NORMAL_STATUS.equals(holder
					.getStrProperty(SET_RETURN_CODE_KEY));
		}

	}

	/*
	 * private void executeMethod(HttpMethod method) { try { statusCode =
	 * httpClient.executeMethod(method); } catch (IOException e) { throw new
	 * VssException(VssConstants.CODE_VISIT_NVS_ERROR); } finally {
	 * method.releaseConnection(); } }
	 */

	private String executeMethodForString(HttpMethod method) {
		String result = null;
		try {
			statusCode = httpClient.executeMethod(method);
			result = method.getResponseBodyAsString();
		} catch (IOException e) {
			throw new VssException(VssConstants.CODE_VISIT_NVS_ERROR);
		} finally {
			method.releaseConnection();
			if (statusCode == 401) {
				throw new VssException(VssConstants.CODE_VS_AUTHENTICATE_FAILED);
			}
		}
		return result == null ? "" : result.trim();
	}

	private GetMethod createSetMethod(String function, String data) {
		GetMethod method = new GetMethod("/Set");
		method.setQueryString(new NameValuePair[] {
				new NameValuePair("Func", function),
				new NameValuePair("Kind", KIND),
				new NameValuePair("Data", data) });
		return method;
	}

	private GetMethod createGetMethod(String function, String KIND) {
		GetMethod method = new GetMethod("/Get");
		method.setQueryString(new NameValuePair[] {
				new NameValuePair("Func", function),
				new NameValuePair("Kind", KIND) });
		return method;
	}

	public boolean setIpcameraMotionDetect(IpCameraAlarmCofig alarmConfig) {
		PropertiesHolder holder = new PropertiesHolder();
		GetMethod method = new GetMethod("/Set");
		method
				.setQueryString(new NameValuePair[] {
						new NameValuePair("Func", "MotionDetect"),
						new NameValuePair("Kind", KIND),
						new NameValuePair("Thresh", alarmConfig.getThresh()
								.toString()),
						new NameValuePair("Sense", alarmConfig.getSense()
								.toString()) });
		String result = executeMethodForString(method);
		holder.load(result);

		return VssConstants.RESULT_NORMAL_STATUS.equals(holder
				.getStrProperty(SET_RETURN_CODE_KEY));
	}

	private String dateFormat(TimeInfo timeInfo) {
		// date format yyyyMMddHHmm
		SimpleDateFormat formatDate = new SimpleDateFormat(PATTERN_TIMESTAMP);
		Calendar cal = Calendar.getInstance();
		try {
			cal.set(timeInfo.getYear().intValue(), timeInfo.getMonth()
					.intValue() - 1, timeInfo.getDate().intValue(), timeInfo
					.getHour().intValue(), timeInfo.getMinute().intValue(),
					timeInfo.getSecond().intValue());

		} catch (Exception e) {

		}
		Date date = cal.getTime();
		return formatDate.format(date);

	}

	/**
	 * private String getModelType() { String vsIP = getAccessInfo().getVsIp();
	 * String modeltype = ""; Object[] info = (Object[]) modelMap.get(vsIP);
	 * synchronized (modelMap) { if (info != null && info.length == 2 && ((Long)
	 * info[1]).longValue() + 600000 > System .currentTimeMillis()) { modeltype =
	 * (String) info[0]; } else { modeltype =
	 * requestVsDeviceInfo().getModelName(); modelMap.put(vsIP, new Object[] {
	 * modeltype, new Long(System.currentTimeMillis()) }); } }
	 * 
	 * return modeltype; }
	 */
	private boolean executeMethod(HttpMethod method) {
		boolean status = false;
		try {
			statusCode = httpClient.executeMethod(method);
			if (VssConstants.NORMAL_STATUS_CODE == statusCode) {
				status = true;
			}
		} catch (IOException e) {
			throw new VssException(VssConstants.CODE_VISIT_NVS_ERROR);
		} finally {
			method.releaseConnection();
		}
		return status;
	}
}
